package city.spring.modules.material.controller;

import city.spring.modules.material.dto.ShelfDTO;
import city.spring.modules.material.entity.ShelfEntity;
import city.spring.modules.material.entity.StorehouseEntity;
import city.spring.modules.material.service.ShelfService;
import city.spring.modules.material.service.StorehouseService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Controller：货架
 *
 * @author 谢金婷
 * @date 2020-07-15 09:55:50
 */
@RestController
@RequestMapping("/shelf")
public class ShelfController extends ApiController {
    private final ShelfService shelfService;
    private final StorehouseService storehouseService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<ShelfEntity, ?>> entityOrderFields;

    public ShelfController(ShelfService shelfService, StorehouseService storehouseService) {
        this.shelfService = shelfService;
        this.storehouseService = storehouseService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(ShelfEntity::getId);
        entityOrderFields.add(ShelfEntity::getStorehouseId);
        entityOrderFields.add(ShelfEntity::getCode);
        entityOrderFields.add(ShelfEntity::getGmtCreate);
        entityOrderFields.add(ShelfEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>货架</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, ShelfEntity entity) {
        LambdaQueryChainWrapper<ShelfEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>货架</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, ShelfEntity entity) {
        LambdaQueryChainWrapper<ShelfEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<ShelfEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        for (ShelfEntity record : page.getRecords()) {
            try {
                StorehouseEntity storehouseEntity = storehouseService.getById(record.getStorehouseId());
                record.setStname(storehouseEntity.getSname());
            } catch (Exception ignore) {
                record.setStorehouseId(null);
                record.setStname("< 找不到仓库 >");
            }
        }
        return success(page);
    }

    /**
     * 获取一个 <strong>货架</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        return success(shelfService.getById(id));
    }

    /**
     * 添加一个 <strong>货架</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody ShelfDTO entity) {
        shelfService.saveShelf(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>货架</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody ShelfDTO entity) {
        entity.setId(id);
        shelfService.updateShelf(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>货架</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        shelfService.deleteShelf(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>货架</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        shelfService.deleteShelf(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<ShelfEntity> buildLambdaQuery(ShelfEntity entity) {
        LambdaQueryChainWrapper<ShelfEntity> lambdaQuery = shelfService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), ShelfEntity::getId, entity.getId());
        lambdaQuery.eq(entity.getStorehouseId() != null, ShelfEntity::getStorehouseId, entity.getStorehouseId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getCode()), ShelfEntity::getCode, entity.getCode());
        lambdaQuery.eq(entity.getGmtCreate() != null, ShelfEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, ShelfEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<ShelfEntity> buildQuery(ShelfEntity entity) {
        QueryWrapper<ShelfEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.eq(entity.getStorehouseId() != null, "storehouse_id", entity.getStorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getCode()), "code", entity.getCode());
        wrapper.eq(entity.getGmtCreate() != null, "gmt_create", entity.getGmtCreate());
        wrapper.eq(entity.getGmtModified() != null, "gmt_modified", entity.getGmtModified());
        return wrapper;
    }


}
